package com.itjeffrey.autocode.util;

import com.itjeffrey.autocode.constant.SysConstant;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件工具类
 *
 * @From: Jeffrey
 * @Date: 2020/11/22
 */
public class FileUtil {

    /**
     * 递归算法查找文件
     *
     * @param rootPath 根目录
     * @return
     */
    public static List<File> searchFiles(String rootPath) {
        File root = new File(rootPath);
        //用于储存找到的每一个文件
        List<File> fileList = new ArrayList<>();
        File[] files = root.listFiles();
        int length = files.length;
        for (int i = 0; i < length; i++) {
            if (files[i].isDirectory()) {
                root = files[i];
                searchFiles(root.getAbsolutePath());
            } else {
                fileList.add(files[i]);
            }
        }
        return fileList;
    }

    /**
     * 统计文件个数和总的大小
     *
     * @param rootPath 根目录
     * @return
     */
    public static Map<String, String> countFiles(String rootPath) {
        Map<String, String> map = new HashMap<>();
        List<File> fileList = searchFiles(rootPath);
        map.put("fileCount", String.valueOf(fileList.size()));
        long totalSize = 0;
        System.out.println("文件数:" + fileList.size());
        for (int i = 0; i < fileList.size(); i++) {
            totalSize += fileList.get(i).length();//返回由此文件的长度，字节为单位
        }
        map.put("totalSize", String.valueOf(totalSize));
        System.out.println("文件总大小:" + totalSize);
        return map;
    }

    /**
     * 根据文件夹路径获取该目录下所有文件名，前提：该目录下没有任何文件夹
     *
     * @param rootPath 根目录
     * @return
     */
    public static List<String> getFileNames(String rootPath) {
        List<String> fileNames = new ArrayList<>();
        File file = new File(rootPath);
        File[] files = file.listFiles();
        for (File f : files) {
            fileNames.add(f.getName().substring(0, f.getName().lastIndexOf(SysConstant.SPECIAL_CHAR_13)));
        }
        return fileNames;
    }

}
